package com.zfei.gfb.util;

import com.zfei.gfb.core.Context;
import org.apache.commons.lang3.RandomUtils;

/**
 * @author fgh
 */
public class Trace {

    public static final String KEY_TRACE = "X-B3-TraceId";

    public static String createTrace() {
        return createTrace(Now.millis());
    }

    public static String createTrace(long millis) {
        return millis + "-" + RandomUtils.nextInt(0, 100000);
    }

    public static String getTrace() {
        return (String) Context.current().getGlobalAttachment(KEY_TRACE);
    }

    public static String setTrace(String trace) {
        Context.current().setGlobalAttachment(KEY_TRACE, trace);
        return trace;
    }

    public static String start() {
        return setTrace(createTrace());
    }

    public static String start(long millis) {
        return setTrace(createTrace(millis));
    }

    public static void stop() {
        setTrace(null);
    }
}
